package com.rtthreadlocal.threadlocalstarter;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>ThreadLocalUtil .
 *
 * <p>change history:
 *
 * <pre>
 * date         defect       person          comments
 * --------------------------------------------------------------------------------
 * 2025/6/2    ********     Tao Ren    create file.
 * </pre>
 *
 * @author Tao Ren
 * @date 2025/6/2 20:44
 */

public class ThreadLocalUtil {
    private static final ThreadLocal<Map<String, Object>> threadLocal = new ThreadLocal<>();
    private static String prefix = "";

    public static void setPrefix(String prefix) {
        ThreadLocalUtil.prefix = prefix;
    }

    public static void set(String key, Object value) {
        String prefixedKey = prefix + key;
        System.out.println("Setting key: " + prefixedKey); // 打印实际使用的键
        Map<String, Object> map = threadLocal.get();
        if (map == null) {
            map = new HashMap<>();
            threadLocal.set(map);
        }
        map.put(prefixedKey, value);
    }

    public static Object get(String key) {
        String prefixedKey = prefix + key;
        System.out.println("Getting key: " + prefixedKey); // 打印实际使用的键
        Map<String, Object> map = threadLocal.get();
        return map != null ? map.get(prefixedKey) : null;
    }

    public static void remove(String key) {
        String prefixedKey = prefix + key;
        System.out.println("Removing key: " + prefixedKey); // 打印实际使用的键
        Map<String, Object> map = threadLocal.get();
        if (map != null) {
            map.remove(prefixedKey);
        }
    }

    public static void clear() {
        threadLocal.remove();
    }
}
